#!/usr/bin/python

# Pack a filesystem into a C array for use by RomFS.
#
# Hugo Vincent, 1 August 2010.

import sys
import fnmatch
import os
from datetime import datetime as dt

if len(sys.argv) != 3:
	print("Usage: build_romfs.py output.c directory/to/pack")
	sys.exit()

output = open(sys.argv[1], "w")

data, header, offset, num_files = "", "", 0, 0

def pack_file(filename, contents):
	global data, header, offset, num_files
	header += "\t{\n\t\t.filename = \"%s\",\n" % filename
	header += "\t\t.offset = 0x%x,\n" % offset
	header += "\t\t.length = %d\n\t},\n" % len(contents)
	data += contents
	offset += len(contents)
	num_files += 1

# Walk the directory tree and process the files, write the header struct
for root, dirs, files in os.walk(sys.argv[2]):
	for filename in files:
		path = os.path.join(root, filename)
		filename = path[path.find('/')+1:] # trim prefix
		contents = open(path, "r").read()
		pack_file(filename, contents)

# Write the concatenated data now
output.write("/* Autogenerated by lib/build_romfs.py on %s */\n" % dt.strftime(dt.now(), "%c"))

output.write("static const unsigned int romfs_numfiles = %s;\n" % num_files)
output.write("static const struct file_entry romfs_header[] = {\n")
output.write(header)
output.write("};\n")

output.write("static const unsigned char romfs_data[] __attribute__ ((aligned(4))) = {")
for char in data:
	output.write(hex(ord(char)) + ", ")
output.write("};\n")

